<template>
  <div class="process-order">
    <div class="product-define full-height page-content"
         style="background-color: #fff; border-radius: 6px">
      <collapse ref="collapse">
        <template v-slot:content>
          <div style="padding: 0 20px 0">
            <div class="form-inline "
                 style="justify-content: space-between; margin-top: 10px ;flex-basis: initial;padding: 0 ">
              <div class="left box" style="display: flex">
              <div class="row">
                <select-tooltip
                  v-model="queryParams.status"
                  isShowAll
                  ref="multipeSelect"
                  :options="statusOptions"
                  msg="工单状态"
                ></select-tooltip>
                <workshop-search v-model="queryParams" ref="workShopSearch" @onReady="onReady" :urlId="viewPrivilegeId"/>
                <div class="margin-b-20 margin-r-20">
                  <span class="form-name" style="margin-right:6px">计划开工:</span>
                  <date-picker format="YYYY-MM-DD"
                               value-type="format"
                               :editable="false"
                               type="date"
                               v-model="queryParams.date"
                               range
                               placeholder="选择时间范围"
                               style="width: 240px" />
                </div>
                <div class="margin-b-20 margin-r-20">
                  <span class="form-name" style="margin-right:6px">实际开工:</span>
                  <date-picker format="YYYY-MM-DD"
                               value-type="format"
                               :editable="false"
                               type="date"
                               v-model="queryParams.processDate"
                               range
                               placeholder="选择时间范围"
                               style="width: 240px" />
                </div>
                <yz-input
                  v-model.trim="queryParams.productSpec"
                  class="q-mr-md"
                  title="产品规格"
                />
              </div>
              </div>
              <div style="display: flex">
                <q-btn class="btn margin-r-10"
                       outline
                       color="primary"
                       label="重置"
                       @click="resetSearch" />
                <q-btn class="btn"
                       unelevated
                       @click="submit"
                       color="primary"
                       label="查询" />
              </div>
            </div>
            <div class="form-inline no-padding flex justify-between">
              <div>
                <q-btn class="btn margin-r-20"
                       outline
                       @click="toPage('overProduction')"
                       color="primary"
                       label="当班超产" />
                <q-btn class="btn"
                       outline
                       @click="toPage('updateData')"
                       v-if="isShowUpdateBtn"
                       color="primary"
                       label="接口更新" />
              </div>
              <div class="flex">
                <select-input ref="selectInput"
                              :list="searchCondition"
                              @search="inputSearch"
                              @clearSearchVal="clearSearchVal" />
              </div>
            </div>
          </div>
        </template>
      </collapse>
      <q-table color="primary"
               style="margin-top: 20px"
               :data="tableData"
               :columns="columns"
               :loading="isTableLoading"
               row-key="id"
               class="myTable scroll stick-last-col"
               :pagination.sync="pagination"
               :hide-bottom="!!tableData.length"
               ref="table">
        <template v-slot:header-cell-id="props">
          <q-th :props="props">
            <div class="inline-block" style="width: 20px"/>
            {{ '工单编号' }}
          </q-th>
        </template>
        <template v-slot:header-cell-createTime="props">
          <q-th :props="props"
                class="sortable"
                :class="[sortBy == 'dispatchTime' ? 'sorted' : '','sort-' +value]"
                @click="sortable('dispatchTime')">
            {{ '派单时间' }}
            <q-icon name="arrow_upward"
                    size="16px"
                    class="q-table__sort-icon" />
          </q-th>
        </template>
        <template v-slot:header-cell-startTime="props">
          <q-th :props="props"
                class="sortable"
                :class="[sortBy == 'startTime' ? 'sorted' : '','sort-' +value]"
                @click="sortable('startTime')">
            计划开工时间
            <q-icon name="arrow_upward"
                    size="16px"
                    class="q-table__sort-icon" />
          </q-th>
        </template>
        <template v-slot:header-cell-operations="props">
          <q-th :props="props">
           操作
            <q-icon name="iconfont icontubiao-72" class="font-18 cursor-pointer margin-l-10" @click="dialogVisible = true" style="margin-top: -3px;color: #999"/>
          </q-th>
        </template>
        <template v-slot:body-cell-id="props">
          <q-td :props="props">
            <div class="inline-block" style="width: 20px">
              <i style="font-size: 14px" class="iconfont icontubiao-10 text-primary" v-if="props.row.isCombinedWorkOrder" />
            </div>
            {{ props.row.id }}
          </q-td>
        </template>
        <template v-slot:body-cell-materialNames="props">
          <q-td :props="props">
            <data-list :is-combined-work-order="props.row.isCombinedWorkOrder" title="加工产品" :data-list="props.row.materialNames"/>
          </q-td>
        </template>
        <template v-slot:body-cell-productStandard="props">
          <q-td :props="props">
            <data-list :is-combined-work-order="props.row.isCombinedWorkOrder" isSpec title="产品规格" :data-list="props.row.productSpecs"/>
          </q-td>
        </template>
        <template v-slot:body-cell-orderNumbers="props">
          <q-td :props="props">
            <data-list :is-combined-work-order="props.row.isCombinedWorkOrder" title="订单号" :data-list="props.row.orderNumbers"/>
          </q-td>
        </template>
        <template v-slot:body-cell-orderBatches="props">
          <q-td :props="props">
            <data-list :is-combined-work-order="props.row.isCombinedWorkOrder" title="批次号" :data-list="props.row.orderBatches"/>
          </q-td>
        </template>
        <template v-slot:body-cell-workshopPlanningNumbers="props">
          <q-td :props="props">
            <data-list :is-combined-work-order="props.row.isCombinedWorkOrder" title="车间计划编号" :data-list="props.row.workshopPlanningNumbers"/>
          </q-td>
        </template>
        <template v-slot:body-cell-orderStatus="props">
          <q-td :props="props">
            <div style="min-width: 76px">
              <div class="status"
                   :style="{backgroundColor: judgeStatus(props.row.orderStatus, 'color' ,props.row.isSuspend)}" />
              <span>{{ judgeStatus(props.row.orderStatus, 'name', props.row.isSuspend) }}</span>
            </div>
          </q-td>
        </template>
        <template v-slot:body-cell-qcStatus="props">
          <q-td :props="props">
            <div v-if="props.row.qcStatus !== null && props.row.qcStatus !== undefined">
              <div class="status"
                   :style="{backgroundColor:judgeStatus(props.row.qcStatus, 'color')}" />
              <span>{{ judgeStatus(props.row.qcStatus, 'name') }}</span>
            </div>
            <div v-else>
              {{ '--' }}
            </div>
          </q-td>
        </template>
        <template v-slot:body-cell-operations="props">
          <q-td class="operations"
                style="width: 200px">
            <div class="btn-group"
                 style="text-align: center">
              <q-btn v-has="{id: Enums.SYS_PERMISSION.START_CHECKIN_WORK_ORDER_BTN.value}"
                     flat
                     color="primary"
                     v-if="props.row.recordChangeoverTime && props.row.orderStatus === 0"
                     @click="clickChangeover(props.row)"
                     class="table-flat-btn">
                换线
              </q-btn>

              <q-btn v-has="{id: Enums.SYS_PERMISSION.START_CHECKIN_WORK_ORDER_BTN.value}"
                     v-else
                     flat
                     color="primary"
                     :disable="!(props.row.orderStatus === 0 || props.row.orderStatus === 4)"
                     class="table-flat-btn"
                     @click="clickStart(props.row)">
                开工
              </q-btn>

              <q-btn v-has="{id: Enums.SYS_PERMISSION.START_CHECKIN_WORK_ORDER_BTN.value}"
                     flat
                     color="primary"
                     :disable="props.row.orderStatus !== 3 || props.row.isSuspend"
                     class="table-flat-btn"
                     @click="clickComplete(props.row)">
                报工
              </q-btn>

              <q-btn v-has="{id: Enums.SYS_PERMISSION.REQUIRE_QC_INSPECTION_BTN.value}"
                     flat
                     color="primary"
                     :disable="judgeOrder('test', props)"
                     class="table-flat-btn"
                     @click="clickTest(props.row)">
                报检
              </q-btn>

              <q-btn v-has="{id: Enums.SYS_PERMISSION.CLOSE_WORK_ORDER_BTN.value}"
                     flat
                     color="primary"
                     :disable="judgeOrder('reverseOrder', props)"
                     class="table-flat-btn"
                     @click="clickReverseOrder(props.row)">
                转序
              </q-btn>
              <q-btn
                flat
                color="primary"
                @click="rightMenu(props)"
                class="table-flat-btn">
                更多
                <q-popup-proxy>
                  <div class="flex column">
                    <q-btn flat color="primary" class="qa-d-text" v-throttle label="详情" @click="onMenuClick('details', props.row)"/>
                    <q-btn flat color="primary" class="qa-d-text" v-throttle label="工单打回"
                           :disable="judgeDisable('singles', props.row)"
                           @click="onMenuClick('singles', props.row)"
                           v-has="{id: Enums.SYS_PERMISSION.TRANSFER_WORK_BACK_BTN.value}"/>
                    <q-btn flat color="primary" class="qa-d-text" v-throttle label="工单修正"
                           :clickable="judgeClickable('amend', props.row)"
                           :disable="judgeDisable('amend', props.row)"
                           @click="onMenuClick('amend')"
                           v-has="{id: Enums.SYS_PERMISSION.CORRECT_WORK_ORDER_COMPLETE_COUNT_BTN.value}"/>
                    <q-btn flat color="primary" class="qa-d-text" v-throttle label="强制完工"
                           :clickable="judgeClickable('forcedCompletion', props.row)"
                           :disable="judgeDisable('forcedCompletion', props.row)"
                           @click="onMenuClick('forcedCompletion')"
                           v-has="{id: Enums.SYS_PERMISSION.FORCE_CLOSE_WORK_ORDER_BTN.value}"/>
                    <q-btn flat color="primary" class="qa-d-text" v-throttle label="强制关闭"
                           :clickable="judgeClickable('close', props.row)"
                           :disable="judgeDisable('close', props.row)"
                           @click="onMenuClick('close')"
                           v-has="{id: Enums.SYS_PERMISSION.FORCE_CLOSE_WORK_ORDER_BTN.value}"/>
                    <q-btn flat color="primary" class="qa-d-text" v-throttle :label="props.row.isSuspend?'恢复加工':'工单暂停'"
                           :clickable="judgeClickable('suspend', props.row)"
                           :disable="judgeDisable('suspend', props.row)"
                           @click="onMenuClick('suspend', props.row)"
                           v-has="{id: Enums.SYS_PERMISSION.FORCE_CLOSE_WORK_ORDER_BTN.value}"/>
                  </div>
                </q-popup-proxy>
              </q-btn>
            </div>
          </q-td>
        </template>
      </q-table>
      <yz-pagination v-model="pagination" @onSearch="getList"/>
    </div>
    <drawer
      title="说明"
      :visible.sync="dialogVisible"
      width="500px"
      close-on-click-modal>
      <div>
        <div v-for="(item, index) in tips" :key="index" class="margin-b-10" style="line-height: 1.5">{{item}}</div>
      </div>
    </drawer>

    <!--工单转移弹出框-->
    <work-order-transfer ref="workOrderTransfer"
                         :show="workOrderTransferDialog.show"
                         @close="workOrderTransferDialog.show = false"
                         @submit="_workOrderTransferSubmit" />

    <!--工单转序-->
    <work-order-reverse ref="workOrderReverse"
                        :show="workOrderReverseDialog.show"
                        @submit="_workOrderReverseSubmit"
                        @close="workOrderReverseDialog.show = false" />
    <!--工单报检弹出框 -->
    <work-order-test ref="workOrderTest"
                     :show="workOrderTestDialog.show"
                     @submit="_workOrderTestSubmit"
                     @close="workOrderTestDialog.show = false" />
    <!--工单产量修正-->
    <work-order-correction-quantity ref="workOrderCorrectionQuantity"
                                    :show="workOrderCorrectionQuantityDialog.show"
                                    @submit="_workOrderCorrectionQuantitySubmit"
                                    @close="workOrderCorrectionQuantityDialog.show = false" />
  </div>
</template>

<script>
import { getViewPrivilegeId } from '../../assets/js/enums'
import SelectInput from 'src/components/select-input'
import WorkOrderTransfer from './components/work-order-transfer'
import WorkOrderReverse from './components/work-order-reverse'
import workOrderCorrectionQuantity from './components/work-order-correction-quantity'
import WorkOrderTest from './components/work-order-test'
import dataList from './components/work-order/detail-list'
import Collapse from 'src/components/collapse'
import _ from 'lodash'
import { mapGetters } from 'vuex'

import {
  getWorkOrders,
  workOrderWithdraw,
  workOrderChangeover,
  workOrderStart,
  workOrderClose,
  orderTransfer,
  orderForceComplete,
  workOrderTest,
  offsetCompleteCount,
  orderForceClose,
  orderSuspend,
  orderRecover, getShiftDate, isShowBtn
} from 'src/boot/job/process-order'
import moment from 'moment'
import Drawer from 'src/components/drawer/drawer'
import { getShifts } from '../../boot/status-monitor/status-overview'
import { getShiftsDate } from '../../boot/home/home-new'

export default {
  name: 'process-order',
  components: {
    SelectInput,
    WorkOrderTransfer,
    WorkOrderReverse,
    workOrderCorrectionQuantity,
    WorkOrderTest,
    Collapse,
    Drawer,
    dataList
  },
  data () {
    return {
      viewPrivilegeId: getViewPrivilegeId('processOrder'),
      tips: [
        '工单打回：工单打回后，未完工数量返回派工任务池。',
        '修正产量：未关闭工单，可修改已有的完工数量。',
        '强制关闭：工单变为关闭状态，系统不支持回退，请慎重进行此操作。'
      ],
      dialogVisible: false,
      isSort: true,
      sortBy: '', // 表格排序依据
      value: '', // 正序or道序
      sort: '', // 最终排序字段
      isTableLoading: false,
      selectedPlan: [], // 选中的数据
      queryParams: {
        productSpec: '',
        location: {
          id: null,
          level: null,
          label: '',
          hash: ''
        },
        devices: ['all'],
        searchBy: '',
        keyword: '',
        date: [],
        processDate: [],
        status: ['all'],
        workshop: null,
        assetNumber: null,
        shift: 'all',
        workshopId: ''
      }, // 查询条件对象
      oldWorkshopId: null, // 列表所属车间
      formData: [], // 右键菜单选中行
      searchCondition: [
        {
          id: 'workOrderNumber',
          name: '工单号',
          statId: this.CommonConfig.statData.processOrder.searchByWorkOrderNum.id
        },
        {
          id: 'orderNumber',
          name: '订单号',
          statId: this.CommonConfig.statData.processOrder.searchByOrderNum.id
        },
        {
          id: 'materialName',
          name: '产品名称',
          statId: this.CommonConfig.statData.processOrder.searchByProductName.id
        },
        {
          id: 'materialNumber',
          name: '产品编号',
          statId: this.CommonConfig.statData.processOrder.searchByMachine.id
        }
        // { id: 'deviceName', name: '加工设备', statId: this.CommonConfig.statData.processOrder.searchByMachine.id }
      ],
      workshopOpt: [], // 所在车间数据源
      // 显示右键菜单
      showPopup: [],
      // 右键菜单是否没有显示。true,已经显示,false没有显示。性能优化用
      hadShowPopup: false,
      tableData: [], // 列表数据源
      columns: [
        { name: 'id', label: '工单编号', field: 'id', align: 'left' },
        { name: 'materialNames', label: '加工产品', field: 'materialNames', align: 'left' },
        { name: 'productStandard', label: '产品规格', field: 'productStandard', align: 'left' },
        { name: 'orderNumbers', label: '订单号', field: 'orderNumbers', align: 'left' },
        { name: 'orderStatus', label: '当前状态', field: 'orderStatus', align: 'left' },
        { name: 'startTime', label: '计划开工时间', field: 'startTime', align: 'left' },
        { name: 'actualStartTime', label: '实际开工时间', field: 'actualStartTime', align: 'left' },
        { name: 'deviceName', label: '加工设备', field: 'deviceName', align: 'left' },
        { name: 'shiftName', label: '加工班次', field: 'shiftName', align: 'left' },
        { name: 'operator', label: '操作员', field: 'operator', align: 'left' },
        { name: 'processName', label: '加工工序', field: 'processName', align: 'left' },
        { name: 'workshopPlanningNumbers', label: '车间计划编号', field: 'workshopPlanningNumbers', align: 'left' },
        { name: 'doQcInspection', label: '是否需要质检', field: 'doQcInspectionStr', align: 'left' },
        { name: 'qcStatus', label: '质检进度', field: 'qcStatus', align: 'left' },
        { name: 'orderBatches', label: '批次号', field: 'orderBatches', align: 'left' },
        { name: 'jobCount', label: '派工数量', field: 'jobCountStr', align: 'left' },
        { name: 'finishedCount', label: '完工数量', field: 'finishedCount', align: 'left' },
        { name: 'rejectionCount', label: '不良数量', field: 'rejectionCount', align: 'left' },
        { name: 'createTime', label: '派单时间', field: 'createTime', align: 'left' },
        { name: 'reportType', label: '报产方式', field: 'reportTypeStr', align: 'left' },
        { name: 'autoStartEnd', label: '自动开完工', field: 'autoStartEndStr', align: 'left' },
        { name: 'operations', field: 'operations', label: '操作', align: 'center' }
      ],
      // 表格分页配置
      pagination: {
        pageNum: 1, // 当前页码
        pageSize: 15, // 每页条数
        rowsNumber: 0 // 总条数
      },
      // 工单转移弹出框
      workOrderTransferDialog: {
        show: false
      },
      // 工单转序弹出框
      workOrderReverseDialog: {
        show: false
      },
      // 工单报检弹出框
      workOrderTestDialog: {
        show: false
      },
      // 产量修正对话框
      workOrderCorrectionQuantityDialog: {
        show: false
      },
      workshopId: '',
      orderId: '',
      selectDate: [],
      deviceId: null,
      isShowUpdateBtn: false
    }
  },
  beforeRouteEnter (to, from, next) {
    if (to.name === 'processOrder' && (from.name === 'qualityOrder' || from.name === 'statsMonitor' || from.name === 'equipmentRecordDetail' || from.name === 'productionDispatch')) {
      next(vm => {
        !_.isEmpty(to.params) ? vm.searchByOrder() : vm.getListInit(vm.queryParams.workshopId === '')
      })
    } else {
      next(vm => {
        vm.getListInit(vm.queryParams.workshopId === '')
      })
    }
  },
  mounted () {
    // 监听table滚动事件，如果滚动就把右键菜单隐藏掉
    const tableDom = this.$refs.table.$el
    if (tableDom) {
      const table = tableDom.querySelector('.q-table__middle')
      if (table) {
        table.onscroll = () => {
          if (this.hadShowPopup) {
            this.hadShowPopup = false
            this.showPopup = this.showPopup.map(() => false)
          }
        }
      }
    }
  },
  computed: {
    ...mapGetters(['userInfo']),
    // 状态枚举
    statusOptions () {
      return this.$getEnum(this.Enums.BUSINESS_STATUS).filter(v => v.workOrder)
    }
  },
  created () {
    this.showUpdateBtn()
  },
  watch: {
  },
  methods: {
    showUpdateBtn () {
      isShowBtn().then(res => {
        this.isShowUpdateBtn = res
      })
    },
    getListInit (isInit = true) {
      isInit ? this.$refs.workShopSearch.getWorkshops().then((res) => {
        this.routeFromName = ''
        this.getList()
      }) : this.getList()
    },
    searchByOrder (isPathByOrder) {
      if (!isPathByOrder) {
        const { workshopId } = this.$route.params
        this.$refs.workShopSearch.initData(false, { workshopId })
      }
    },
    // 赋值成功
    onReady () {
      if (this.$route.params?.orderId) {
        this.queryParams.devices = ['all']
        this.$refs.selectInput.setVal(this.$route.params?.orderId, 0)
      }
    },
    // 获取列表数据
    getList () {
      let isSuspend = false
      this.isTableLoading = true
      this.selectedPlan = []
      let plannedSince = this.queryParams.date[0]
      let plannedBefore = this.queryParams.date[1] ? moment(this.queryParams.date[1]).add(1, 'days').format('YYYY-MM-DD') : null
      let processSince = this.queryParams.processDate[0]
      let processBefore = this.queryParams.processDate[1] ? moment(this.queryParams.processDate[1]).add(1, 'days').format('YYYY-MM-DD') : null

      if (this.status === 13) {
        // 当状态为13时说明为暂停状态
        isSuspend = true
      }
      this.oldWorkshopId = this.queryParams.workshopId
      const { location } = this.queryParams
      const params = {
        searchBy: _.isNil(this.queryParams.searchBy) || _.isEmpty(this.queryParams.searchBy) ? undefined : this.queryParams.searchBy,
        keyword: _.isNil(this.queryParams.keyword) || _.isEmpty(this.queryParams.keyword) ? undefined : this.queryParams.keyword,
        plannedBefore: _.isNil(plannedBefore) || _.isEmpty(plannedBefore) ? undefined : plannedBefore,
        plannedSince: _.isNil(plannedSince) || _.isEmpty(plannedSince) ? undefined : plannedSince,
        processBefore: _.isNil(processBefore) || _.isEmpty(processBefore) ? undefined : processBefore,
        processSince: _.isNil(processSince) || _.isEmpty(processSince) ? undefined : processSince,
        pageNum: this.pagination.pageNum,
        pageSize: this.pagination.pageSize,
        shiftId: this.queryParams.shift === 'all' ? null : this.queryParams.shift,
        sort: _.isNil(this.sort) || _.isEmpty(this.sort) ? undefined : this.sort,
        assetNumber: _.isNil(this.queryParams.assetNumber) || _.isEmpty(this.queryParams.assetNumber) ? undefined : this.queryParams.assetNumber,
        isSuspend
      }
      params.deviceTreeReqVO = {
        deviceIds: this.queryParams.devices[0] !== 'all' ? this.queryParams.devices : [],
        level: location.level || null,
        schemeId: location.id || null
      }
      if (this.queryParams.status[0] !== 'all') {
        params['statusCodeList'] = this.queryParams.status
      }
      if (_.isEmpty(params.deviceTreeReqVO.deviceIds) && _.isNil(params.deviceTreeReqVO.level) && _.isNil(params.deviceTreeReqVO.schemeId)) {
        this.$message.warning('请选择所在位置')
        this.isTableLoading = false
        return
      }
      this.queryParams.productSpec + '' !== '' && (params['productSpec'] = this.queryParams.productSpec)
      getWorkOrders(params).then(res => {
        this.isTableLoading = false
        res.data.list.forEach(o => {
          o.id = o.groupId
          o.autoStartEndStr = o.autoStartEnd ? '自动' : '手动'
          o.reportTypeStr = o.reportType === 0 ? '自动报产' : '手动报产'
          o.jobCountStr = o.jobCount === 0 ? '不足0.1' : o.jobCount
          o.doQcInspectionStr = o.doQcInspection ? '是' : '否'
          o.createTime = o.createTime ? this.$utils.formatDatetime(o.createTime) : '--'
          o.startTime = o.startTime ? this.$utils.formatDatetime(o.startTime) : '--'
          o.endTime = o.endTime ? this.$utils.formatDatetime(o.endTime) : '--'
          o.actualStartTime = o.actualStartTime ? this.$utils.formatDatetime(o.actualStartTime) : '--'
          o.actualEndTime = o.actualEndTime ? this.$utils.formatDatetime(o.actualEndTime) : '--'
          o.shiftName = this.$utils.label(o.shiftName)
          o.finishedCount = this.$utils.label(o.finishedCount, 0)
          o.rejectionCount = this.$utils.label(o.rejectionCount, 0)
          o.needQcCount = this.$utils.label(o.needQcCount, 0)
          o.deviceName = `${this.$utils.label(o.deviceName)}(${this.$utils.label(o.deviceNumber)})`
          o.processName = `${o.isCombinedWorkOrder ? '' : (o.processSort + 1) + '-'}${this.$utils.label(o.processName)}`
          o.operator = o.operator ? o.operator : '--'
        })
        this.tableData = res.data.list
        this.pagination.rowsNumber = res.data.total
        this.showPopup = res.data.list.map(() => false)
      })
      this.showPopup = this.tableData.map(() => false)
    },

    // 表格排序
    sortable (type) {
      this.tableData = []
      if (this.sortBy === type) {
        if (this.value) {
          this.value = this.value === 'asc' ? 'desc' : 'asc'
        } else {
          this.value = 'asc'
        }
      } else {
        this.sortBy = type
        this.value = 'asc'
      }
      this.value === 'asc'
        ? (this.sort = `${this.sortBy}+`)
        : (this.sort = `${this.sortBy}-`)
      this.pagination.pageNum = 1
      this.getList()
    },
    // 查询按钮
    submit () {
      this.pagination.pageNum = 1
      // 无设备时直接清空列表不再请求
      if (this.queryParams.devices.length) {
        this.getList()
      } else {
        this.tableData = []
        this.pagination.rowsNumber = 0
      }
    },
    resetSearch () {
      this.queryParams.status = ['all']
      this.queryParams.assetNumber = null
      this.queryParams.date = []
      this.queryParams.processDate = []
      this.queryParams.productSpec = ''
      this.$refs.workShopSearch.initData()
    },
    // 模糊查询
    inputSearch (item, searchVal) {
      this.pagination.pageNum = 1
      this.queryParams.keyword = searchVal
      this.queryParams.searchBy = item.id
      this.getList()
    },

    // 清空搜索值
    clearSearchVal () {
      this.queryParams.keyword = ''
      this.queryParams.searchBy = ''
      this.pagination.pageNum = 1
      this.getList()
    },
    // 点击右键菜单
    rightMenu (props) {
      this.selectedPlan = [props.row]
      this.formData = [props.row]
      this.hadShowPopup = true
    },

    // 点击右键菜单
    onMenuClick (type, row) {
      this.showPopup = this.showPopup.map(() => false)
      this.hadShowPopup = false
      switch (type) {
        case 'details':
          this.clickOrderDetails(this.formData, row)
          break
        case 'transfer':
          this.clickOrderTransfer(this.formData)
          break
        case 'amend':
          this.clickOrderAmend(this.formData)
          break
        case 'forcedCompletion':
          this.clickOrderForcedCompletion(this.formData)
          break
        case 'singles':
          this.onGetSinglesData(row)
          break
        case 'close':
          this.clickOrderClose(this.formData)
          break
        case 'suspend':
          this.suspendOrRecover(row)
          break
      }
    },

    // 工单换线
    clickChangeover (row) {
      this.selectedPlan = [row]
      this.$utils.showMessage('icontubiao-28', `是否确认换线?`, () => {
        workOrderChangeover(row.id).then(res => {
          if (res.code === '1200') {
            this.getList()
            this.$message.success('换线成功')
          }
        })
      }, true)
    },

    // 工单开工
    clickStart (row) {
      let ret = row.isSuspend && row.orderStatus === 4
      if (ret) {
        this.$utils.showMessage('icontubiao-28', `当前工单为暂停状态，开工后工单仍为暂停状态，请确认是否开工？`, () => {
          this.$q.loading.show()
          this.selectedPlan = [row]
          this.getShiftsDate(row)
        }, true)
      } else {
        this.$q.loading.show()
        this.selectedPlan = [row]
        this.getShiftsDate(row)
      }
      // const nowDay =
      //   moment(new Date()).format('YYYY-MM-DD') ===
      //   moment(row.startTime).format('YYYY-MM-DD')
    },
    workOrderStart (id, isOver) {
      this.$q.loading.hide()
      const nowMsg = isOver ? '非当前班制工单,' : ''
      this.$utils.showMessage('icontubiao-28', `${nowMsg}是否确认开工?`, () => {
        workOrderStart(id).then(res => {
          if (res.code === '1200') {
            this.getList()
            this.$message.success('开工成功')
          }
        })
      }, true)
    },
    // 获取班制时间
    getShiftsDate (row) {
      getShiftsDate(this.oldWorkshopId).then(res => {
        if (res) {
          this.getShifts(res, row)
        } else {
          this.$message.warning('请先在“基础数据-工厂日历”里设置班制！')
          this.workOrderStart(row.id, true)
        }
      }).catch(() => {
        this.workOrderStart(row.id, true)
      })
    },
    getShifts (date, row) {
      getShifts(this.oldWorkshopId).then(res => {
        if (res.data) {
          const shifts = _.cloneDeep(res.data)
          shifts.startTime = this.getTime(res.data.startTime)
          shifts.endTime = this.getTime(res.data.endTime)
          if (shifts.startTime && shifts.endTime) {
            // 有班制时间
            const { start, end } = this.getDateTime(shifts, date)
            const isBetween = moment(row.startTime).isBetween(start, end, null, '[]')
            console.log(isBetween, row.startTime, start, end)
            this.workOrderStart(row.id, !isBetween)
          } else {
            this.workOrderStart(row.id, true)
          }
        }
      }).catch(() => {
        this.workOrderStart(row.id, true)
      })
    },
    // 获取时间
    getTime (time) {
      let label = ''
      if (time) {
        let timeArr = time.split(':')

        label = timeArr[0] + ':' + timeArr[1]
      }
      return label
    },
    // 根据时分获取日期时间
    getDateTime (shift = _.cloneDeep(this.shifts), date) {
      let dateObj = {}
      if (date) {
        const dateArr = _.split(date, '-')
        dateObj = {
          year: dateArr[0],
          month: dateArr[1] - 1, // moment月份需-1
          date: dateArr[2]
        }
      }
      let startArr = _.split(shift.startTime, ':')
      let startDateTime = moment().set({ ...dateObj, hours: Number(startArr[0]), minutes: Number(startArr[1]), seconds: 0 })

      let endArr = _.split(shift.endTime, ':', 2)
      let endDateTime = moment().set({ ...dateObj, hours: Number(endArr[0]), minutes: Number(endArr[1]), seconds: 0 })

      shift.isStartTimeOnNextDay && startDateTime.add(1, 'd')
      shift.isEndTimeOnNextDay && endDateTime.add(1, 'd')

      const params = {
        start: startDateTime.format('YYYY-MM-DDTHH:mm:ss'),
        end: endDateTime.format('YYYY-MM-DDTHH:mm:ss')
      }
      return params
    },

    // 工单报工
    clickComplete (row) {
      this.selectedPlan = [row]
      this.$router.push({
        name: 'completeOrder',
        params: {
          ...row
        }
      })
    },

    // 工单报检
    clickTest (row) {
      this.selectedPlan = [row]
      this.workOrderTestDialog.show = true
      row.count = null
      this.$refs.workOrderTest.assignment(row)
    },

    // 工单报检提交
    _workOrderTestSubmit (query) {
      workOrderTest(query).then(res => {
        if (res.code === '1200') {
          this.getList()
          this.workOrderTestDialog.show = false
          this.$message.success('报检成功')
        }
      }).finally(() => {
        this.$refs.workOrderTest.hideLoading()
      })
    },

    // 工单转序
    clickReverseOrder (row) {
      const item = _.cloneDeep(row)
      this.selectedPlan = [item]
      this.workOrderReverseDialog.show = true
      this.$refs.workOrderReverse.assignment(item)
    },

    // 工单转序提交
    _workOrderReverseSubmit (form) {
      // 考虑是不是末序
      workOrderClose(form.id, form.comments).then(res => {
        if (res.code === '1200') {
          this.getList()
          this.workOrderReverseDialog.show = false
          this.$message.success('转序成功,工单已关闭')
        }
      }).finally(() => {
        this.$refs.workOrderReverse.hideLoading()
      })
    },

    // 工单详情
    clickOrderDetails (val, row) {
      // console.log(val, row, '1111111111')
      this.$router.push({
        name: 'processOrderDetail',
        params: {
          ...row
        }
      })
      // this.workOrderDetailsDialog.show = true
      // this.$refs.workOrderDetails.assignment(val, row)
    },

    // 工单转移
    clickOrderTransfer (row) {
      this.$refs.workOrderTransfer.reset()
      this.workOrderTransferDialog.show = true
      this.$refs.workOrderTransfer.assignment(row)
    },

    // 工单转移提交
    _workOrderTransferSubmit (workOrderId, query) {
      orderTransfer(workOrderId, query).then(res => {
        if (res.code === '1200') {
          this.getList()
          this.workOrderTransferDialog.show = false
          this.$message.success('工单转移成功')
        }
      })
    },

    // 产量修正
    clickOrderAmend (val) {
      this.$refs.workOrderCorrectionQuantity.reset()
      this.workOrderCorrectionQuantityDialog.show = true
      this.$refs.workOrderCorrectionQuantity.assignment(val)
    },

    // 产量修正提交
    _workOrderCorrectionQuantitySubmit (form) {
      const query = {}
      query.offset = form.count
      query.shiftId = form.shiftId
      query.operatorId = form.operatorId
      query.operatorName = form.operatorName
      query.day = form.day
      query.remark = form.remark
      offsetCompleteCount(form.id, query).then(res => {
        if (res.code === '1200') {
          this.getList()
          this.workOrderCorrectionQuantityDialog.show = false
          this.$message.success('产量修正成功')
        }
      }).finally(() => {
        this.$refs.workOrderCorrectionQuantity.hideLoading()
      })
    },

    // 强制完工
    clickOrderForcedCompletion (val) {
      this.$utils.showMessage('icontubiao-28', `确定要强制完工此工单吗?`, () => {
        orderForceComplete(val[0].id).then(res => {
          if (res.code === '1200') {
            this.getList()
            this.$message.success('该工单已强制完工')
          }
        })
      }, true)
    },
    // 工单打回 api
    onGetSinglesData (val) {
      const quantity = new this.$Big(val.jobCount).minus(val.finishedCount)
      this.$q
        .dialog({
          title: `<p class="dialog-notice-title"><i class="iconfont icontubiao-28"></i>
          确定要未完工数量打回任务池吗？</p>
          <p style="font-size:14px;margin-left: 30px;">未完工数量:${quantity}</p>`,
          html: true,
          ok: {
            unelevated: true,
            label: '确认'
          },
          cancel: {
            unelevated: true,
            outline: true,
            label: '取消'
          }
        })
        .onOk(() => {
          workOrderWithdraw(val.id).then(res => {
            if (res.code === '1200') {
              this.getList()
              this.$message.success('该工单已打回')
            }
          })
        })
    },
    // 强制关闭
    clickOrderClose (val) {
      this.$utils.showMessage('icontubiao-28', `确定要强制关闭此工单吗?`, () => {
        orderForceClose(val[0].id).then(res => {
          if (res.code === '1200') {
            this.getList()
            this.$message.success('该工单已强制关闭')
          }
        })
      }, true)
    },
    // 工单暂停或恢复加工
    suspendOrRecover (val) {
      if (!val.isSuspend) {
        this.$utils.showMessage('icontubiao-28', `确定要暂停此工单吗?`, () => {
          orderSuspend(val.id).then(res => {
            if (res.code === '1200') {
              this.getList()
              this.$message.success('该工单已暂停')
            }
          })
        }, true)
      } else {
        this.$utils.showMessage('icontubiao-28', `确定要恢复此工单吗?`, () => {
          orderRecover(val.id).then(res => {
            if (res.code === '1200') {
              this.getList()
              this.$message.success('该工单已恢复')
            }
          })
        }, true)
      }
    },

    // 判断操作按钮能否点击
    judgeOrder (condition, props) {
      // 非暂停状态右侧操作按钮才可以点亮  isSuspend
      if (props.row.isSuspend) {
        return true
      }
      if (condition === 'test') {
        // 工单必须有操作员
        // 工单必须是质检工单
        // 若工单状态不为完工或者已经报检过不允许点击报检
        // let ret = false
        // props.row.operator === '' ||
        // props.row.doQcInspection === false ||
        //   props.row.orderStatus !== 5 ||
        //   props.row.hasQcOrder
        let ret = false
        // 先行判断 是否是完工状态, 如果不是 直接返回 true 不让点击报检
        // 1 是否需要质检 2开工或完工状态 3 待报检数量大于0
        if (props.row.doQcInspection) {
          ret = !((props.row.orderStatus === this.Enums.BUSINESS_STATUS.COMPLETE.value || props.row.orderStatus === this.Enums.BUSINESS_STATUS.START.value) &&
          props.row.needQcCount - (props.row.qualityControlledCount || 0) > 0)
        } else {
          ret = true
        }
        return ret
      } else if (condition === 'reverseOrder') {
        // 需要质检 => 是
      // if(是否需要质检) {
      //  if (是否完工) {
      //     if(待检数量 < 1) {
      //       if(该工单下有没有质检单) {
      //         if(质检进度是否为关闭) {
      //           转序
      //         } else {
      //           不允许转序
      //         }
      //       } else {
      //         转序
      //       }
      //     } else {
      //       不允许转序
      //     }
      //  } else {
      //    不允许转序
      //  }
      //  } else {
      //    if (是否完工) {
      //      转序
      //    }
      //  }
      // 否
        const status = [
          props.row.orderStatus === this.Enums.BUSINESS_STATUS.COMPLETE.value, // 完工
          props.row.doQcInspection // 不需要质检
        ]
        const isOrder = [
          props.row.needQcCount - (props.row.qualityControlledCount || 0) < 1, // 待检数量 < 1
          props.row.hasQcOrder // 该工单下没有质检单
        ]
        const isQcStatus = props.row.qcStatus === this.Enums.BUSINESS_STATUS.CLOSE.value // 质检进度是为关闭
        if (status[0] && !status[1]) {
          // 完工+ 不需要质检
          return false
        } else if (status[0] && status[1]) {
          // 完工 + 需要质检
          if (isOrder[0] && isOrder[1]) {
            // 待检数量 < 1 + 有质检单
            return !isQcStatus// 关闭可以转序
          } else if (isOrder[0] && !isOrder[1]) {
            // 待见数量 < 1 + 没有质检单
            return false
          } else {
            // 其他情况 不准转序 包括其他情况
            return true
          }
        } else {
          return true
        }
      }
    },
    // 报检逻辑判断 返回true 不让报检 false 让报检
    isTest (row) {
      // 先行判断 是否是完工状态, 如果不是 直接返回 true 不让点击报检
      // 1 是否需要质检 2 完工数量>0 3 质检进度不为关闭 4 待报检数 != 0 5 开工状态
      const isTest = [
        row.finishedCount > 0, // 完工数量>0
        // row.qcStatus !== this.Enums.BUSINESS_STATUS.CLOSE.value, // 质检进度不为关闭
        row.doQcInspection, // 需要质检
        row.orderStatus === this.Enums.BUSINESS_STATUS.COMPLETE.value ||
          row.orderStatus === this.Enums.BUSINESS_STATUS.START.value, // 开工或者完工
        row.finishedCount - (row.qualityControlledCount || 0) > 0 // 待报检数 > 0
      ]
      return (isTest.indexOf(false) > -1) && !row.isSuspend
    },
    // 转序判断
    isReverseOrder (row) {

    },
    // 判断右键菜单能否被点击
    judgeClickable (condition, row) {
      if (condition === 'details') {
        // 查看详情
      } else if (condition === 'transfer') {
        let ret = false
        row.orderStatus === 3 &&
        row.finishedCount > 0 &&
        parseInt(row.jobCount) - parseInt(row.finishedCount) > 0
          ? (ret = true)
          : (ret = false)
        // 工单转移
        return ret
      } else if (condition === 'singles') {
        // 1 完工数量不为0 2 状态为开工 可以点击
        return (
          this.Enums.PLAN_STATUS.STARTED.value === 3 &&
          row.jobCount - row.finishedCount > 0
        )
      } else if (condition === 'amend') {
        // 产量修正
        let ret = false
        row.orderStatus !== 10 &&
        row.finishedCount > 0
          ? (ret = true)
          : (ret = false)
        return ret
      } else if (condition === 'forcedCompletion') {
        //  强制完工
        let ret = false
        row.orderStatus !== 5 && row.orderStatus !== 10
          ? (ret = true)
          : (ret = false)
        return ret
      } else if (condition === 'close') {
        // 强制关闭
        let ret = false
        row.orderStatus !== 10 ? (ret = true) : (ret = false)
        return ret
      } else if (condition === 'suspend') {
        // 工单暂停或恢复
        let ret = false
        // 开工或换线状态并且为非暂停状态时 或工单为暂停状态时返回true
        ret = row.isSuspend || ((row.orderStatus === 3 || row.orderStatus === 4) && !row.isSuspend)
        return ret
      }
    },

    // 判断右键菜单是否置灰
    judgeDisable (condition, row) {
      if (condition === 'details') {
        // 查看详情
      } else if (condition === 'transfer') {
        // 工单转移
        let ret = false
        row.orderStatus !== 3 ||
        row.finishedCount <= 0 ||
        parseInt(row.jobCount) - parseInt(row.finishedCount) <= 0
          ? (ret = true)
          : (ret = false)
        // 工单转移
        return ret
      } else if (condition === 'singles') {
        return !(
          this.Enums.PLAN_STATUS.STARTED.value === row.orderStatus && !row.isSuspend &&
          row.jobCount - row.finishedCount > 0
        )
      } else if (condition === 'amend') {
        // 产量修正
        let ret = false
        row.orderStatus !== this.Enums.PLAN_STATUS.COMPLETE.value || row.finishedCount <= 0
          ? (ret = true)
          : (ret = false)
        // console.log(ret, 'ret')
        // if (!ret) {
        //   row.qcStatus === this.Enums.BUSINESS_STATUS.CLOSE.value ? (ret = true) : (ret = false)
        // }
        // console.log(condition, ret)
        return ret
      } else if (condition === 'forcedCompletion') {
        // 强制完工(仅开工状态可点)
        // 无报工数量，不可强制完工
        let ret = row.isSuspend || !(row.orderStatus === 3 && row.finishedCount)
        // row.orderStatus === 5 || row.orderStatus === 10 || row.orderStatus === 0 || row.orderStatus === 4
        //   ? (ret = true)
        //   : (ret = false)
        return ret
      } else if (condition === 'close') {
        // 强制关闭
        let ret = false
        row.orderStatus === 10 ? (ret = true) : (ret = false)
        return ret
      } else if (condition === 'suspend') {
        // 工单暂停或恢复加工
        let ret = false
        ret = !(row.isSuspend || ((row.orderStatus === 3 || row.orderStatus === 4) && !row.isSuspend))
        return ret
      }
    },

    // 过滤状态枚举
    judgeStatus (statusCode, type, bool) {
      let statusCodeNew = statusCode
      if (bool) {
        statusCodeNew = 13
      }
      if (type === 'name') {
        let name = ''
        this.statusOptions.forEach(o => {
          if (o.value === statusCodeNew) {
            name = o.label
          }
        })
        return name
      } else {
        let color = ''
        this.statusOptions.forEach(o => {
          if (o.value === statusCodeNew) {
            color = o.color
          }
        })
        return color
      }
    },

    // 当班超产按钮
    toPage (pageName) {
      this.$router.push({ name: pageName })
    },
    // 获取当前车间的班次日期
    getShiftDate () {
      const workshopId = this.queryParams.workshopId
      return new Promise(resolve => {
        if (workshopId) {
          getShiftDate(workshopId).then(res => {
            if (res.data && /^\d{4}(-)(1[0-2]|0?\d)\1([0-2]\d|\d|30|31)$/.test(res.data)) {
              this.queryParams.date = [res.data, res.data]
            } else {
              this.queryParams.date = []
            }
            resolve()
          })
        } else {
          resolve()
        }
      })
    }
  }
}
</script>

<style scoped lang="stylus">
.status
  width 10px
  height 10px
  border-radius 50%
  display inline-block
  margin-right 5px
.negative
  color $negative
.primary
  color $primary
.secondary
  color $secondary
.accent
  color $accent
.positive
  color $positive
.info
  color $info
.warning
  color $warning
>>>.q-table{
  td,th{
    border-left 1px solid #d3d3d3
    &:first-child, &:last-child{
      border-left 0
    }
  }
}
</style>
